package com.hx.base.servlet.excel;

import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import jxl.Workbook;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
 * excel导出 操作类
 * 
 * @filename ExportUtil.java
 * @package com.neili.util.excel
 * 
 * @author alex
 * @version $Id
 * @modify 2011-7-05 上午09:45:44
 */
public class ExcelExport {
	@SuppressWarnings("unchecked")
	public static void export(List list, OutputStream os) {
		List<String> titles = new ArrayList();
		Hashtable<String, List> data = parseData(list, titles);
		try {
			builderExcel(data, titles, list.size(), os);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private static void builderExcel(Hashtable<String, List> data,
			List<String> titles, int len, OutputStream os) throws Exception {
		WritableWorkbook workbook = Workbook.createWorkbook(os);
		WritableSheet ws = workbook.createSheet("sheet1", 0);//  
		for (int i = 0; i < titles.size(); i++) {
			Label labelC = new Label(i, 0, titles.get(i));
			ws.setColumnView(i, 20);
			ws.addCell(labelC);

		}
		for (int i = 0; i < len; i++) {
			for (int j = 0; j < titles.size(); j++) {
				List<Object> context = data.get(titles.get(j));
				Object o = context.get(i);
				o = o==null?"":o;
				WritableCell labelC = null;
				if (o instanceof String) {
					labelC = new Label(j, i + 1, o.toString());
				} else if (o instanceof Double) {
					labelC = new jxl.write.Number(j, i + 1, (Double) o);
				} else if (o instanceof Date) {
					labelC = new DateTime(j, i + 1, (Date) o);
				}
				ws.addCell(labelC);
			}
		}
		workbook.write();
		workbook.close();
	}

	@SuppressWarnings("unchecked")
	private static Hashtable parseData(List list, List titles) {
		Hashtable<String, List> data = new Hashtable<String, List>();
		for (Object obj : list) {
			Method[] methods = obj.getClass().getMethods();
			for (Method m : methods) {
				if (m.isAnnotationPresent(Excel.class)) {
					Excel excel = m.getAnnotation(Excel.class);
					String title = excel.title();
					List<Object> cols = data.get(title);
					if (cols == null) {
						titles.add(title);
						cols = new ArrayList<Object>();
					}
					try {
						cols.add(m.invoke(obj));
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
					data.put(title, cols);
				}
			}
		}
		return data;
	}
}
